/**
 * Copyright 2016 JustWayward Team
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.htfyun;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.OwnerSurfaceView;
import android.view.View;
import android.widget.FrameLayout;

import com.htfyun.pdfview.PDFViewPager;
import com.htfyun.utils.DebugLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.geometerplus.android.fbreader.api.FBReaderIntents;
import org.geometerplus.android.fbreader.libraryService.BookCollectionShadow;
import org.geometerplus.fbreader.book.Book;
import org.geometerplus.fbreader.book.Bookmark;
import org.geometerplus.zlibrary.core.util.RationalNumber;
import org.geometerplus.zlibrary.ui.android.R;

import java.io.File;

@EActivity(R.layout.htfyun_activity_pdf_system)


public class ReadPDFActivity_bk extends AppCompatActivity {

    public static void start(Context context, String filePath) {
        Intent intent = new Intent(context, ReadPDFActivity_bk.class);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.fromFile(new File(filePath)));
        context.startActivity(intent);
    }

    private BookCollectionShadow myCollection;
    private volatile Book myBook;
    private volatile Bookmark myBookmark;

    @ViewById
    FrameLayout llPdfRoot;

    @ViewById
    OwnerSurfaceView pwdraw_surface_view;

    @ViewById
    View layoutFunc;

    private PDFViewPager pdfViewPager;


    @Click(R.id.btnPdfPostil)
    void onClickBtnPdfPostil(){

//        pwdraw_surface_view.setVisibility(View.VISIBLE);
//        pwdraw_surface_view.setHostView(llPdfRoot, null, false);
//        pwdraw_surface_view.setDrawObjectType(OwnerSurfaceView.DRAW_OBJ_RANDOM);

    }

    @Override

    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @AfterViews
    void afterViews() {

        layoutFunc.setVisibility(View.GONE);

        myCollection = new BookCollectionShadow();
        myBook = FBReaderIntents.getBookExtra(getIntent(), myCollection);
        if (myBook == null) {
            finish();
        }
        myBookmark = FBReaderIntents.getBookmarkExtra(getIntent());

        setTitle(myBook.getTitle());

        ActionBar bar = getSupportActionBar();
        if (bar != null) {
            bar.setDisplayHomeAsUpEnabled(true);
        }

        DebugLog.e("book id = " + myBook.getId() + ", book path = " + myBook.getPath());
        displayFromFile((myBook.getPath()));

        myCollection.bindToService(this, new Runnable() {
            @Override
            public void run() {
                myCollection.saveBook(myBook);
                myCollection.addToRecentlyOpened(myBook);
            }
        });
    }

    private void displayFromFile(String filePath) {
        pdfViewPager = new PDFViewPager(this, filePath);

        pdfViewPager.setMiddleClick(new PDFViewPager.IMiddleClick() {
            @Override
            public void onMiddleClick() {
                ReadPDFActivity_bk.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

//                        if (layoutFunc.getVisibility() == View.GONE) {
//                            layoutFunc.setVisibility(View.VISIBLE);
//                        } else {
//                            layoutFunc.setVisibility(View.GONE);
//                        }

                    }
                });
            }
        });

        RationalNumber progress = myBook.getProgress();
        if (progress != null) {
            DebugLog.e("displayFromFile position = " + (int) progress.Numerator);

            pdfViewPager.setCurrentItem((int) progress.Numerator);
        }
        pdfViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                DebugLog.e("onPageSelected position = " + position);

//                RationalNumber progress = myBook.getProgress();

                final long count = (long) pdfViewPager.getAdapter().getCount();

                RationalNumber newProgress = RationalNumber.create(position,  count);
                myBook.setProgress(newProgress);

                myCollection.saveBook(myBook);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        llPdfRoot.addView(pdfViewPager);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                DebugLog.e("onkeydown finish");
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        DebugLog.e("onDestroy");
        if (pdfViewPager != null) {
            pdfViewPager.close();
            pdfViewPager = null;
        }

        if (myCollection != null) {
            myCollection.unbind();
            myCollection = null;

        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            DebugLog.e("onkeydown finish");

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


}
